package org.slsale.controller.user;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.slsale.common.Constants;
import org.slsale.pojo.Authority;
import org.slsale.pojo.Function;
import org.slsale.pojo.Menu;
import org.slsale.pojo.User;
import org.slsale.service.function.FunctionService;
import org.slsale.service.user.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class LoginController extends BaseController {

	private Logger logger = Logger.getLogger(LoginController.class);

	@Resource
	private UserService userService;
	@Resource
	private FunctionService functionService;

	@RequestMapping("/main.html")
	public ModelAndView main(HttpSession session) {
		User user = this.getCurrentUser();
		List<Menu> mList = null;
		if (user != null) {
			Map<String, Object> model = new HashMap<String, Object>();
			model.put("user", user);
			// 根据当前用户获取菜单列表
			mList = getFuncByCurrentUser(user.getRoleId());
			// json
			if (mList != null) {
				JSONArray jsonArray = JSONArray.fromObject(mList);
				String jsonString = jsonArray.toString();
				model.put("mList", jsonString);
				session.setAttribute(Constants.SESSION_BASE_MODEL, model);
				return new ModelAndView("main", model);
			}

		}

		logger.debug("main===" + user.getLoginCode());
		return new ModelAndView("redirect:/");
	}

	// 根据当前用户角色ID获取功能列表
	protected List<Menu> getFuncByCurrentUser(Integer roleId) {
		List<Menu> menuList = new ArrayList<Menu>();
		Authority authority = new Authority();
		authority.setRoleId(roleId);
		try {
			List<Function> mList = functionService
					.getMainFuntionList(authority);
			if (mList != null) {
				for (Function function : mList) {
					Menu menu = new Menu();
					menu.setMainMenu(function);
					function.setRoleId(roleId);
					List<Function> subList = functionService
							.getSubFunctionList(function);
					if (subList != null) {
						menu.setSubMenu(subList);
					}
					menuList.add(menu);
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return menuList;
	}

	@RequestMapping("/login.html")
	@ResponseBody
	// 异步方法提交是使用，表示controller返回的是一个对象
	public Object login(HttpSession session, @RequestParam String user) {
		if (user == null || user == "") {
			return "nodata";
		} else {
			JSONObject userObject = JSONObject.fromObject(user);
			User userObj = (User) userObject.toBean(userObject, User.class);
			try {
				if (userService.loginCodeIsExit(userObj) == 0) {
					return "nologincode";
				} else {
					User _user = userService.getLoginUser(userObj);
					if (_user != null) {// 登录成功,并把当前用户存放到session中
						session.setAttribute(Constants.SESSION_USER, _user);
						// 更新当前用户登陆的lastLoinTime
						User updateLoginTimeUser = new User();
						updateLoginTimeUser.setId(_user.getId());
						updateLoginTimeUser.setLastLoginTime(new Date());
						userService.modifyUser(updateLoginTimeUser);
						updateLoginTimeUser = null;
						return "success";
					} else {// 密码错误
						return "pwderror";
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				return "failed";
			}
		}
	}
}
